package cn.chencq.spider.novel.service.book.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.chencq.spider.novel.service.AbstractSpider;
import cn.chencq.spider.novel.service.book.IBookSpider;
import cn.chencq.spider.novel.utils.SpiderRuleUtils;
import cn.chencq.spider.novel.utils.Utils;
import cn.chencq.spider.novel.vo.Book;
import cn.chencq.spider.novel.vo.Selector;

public class BookSpider extends AbstractSpider implements IBookSpider {

	@Override
	public List<Book> getsBook(String url) {
		List<Book> bookList = new ArrayList<Book>();
		try {
			Document doc = super.crawl(url);
			String domain = Utils.getDomain(url);// 获取链接的主站域名
			Selector selector = SpiderRuleUtils.getSpiderSelector(domain);
			Elements trs = doc.select(selector.getBookListSelector());
			for (Element tr : trs) {
				String bookName = getHtml(tr, selector.getBookNameSelector());
				String bookUrl = getAbsUrl(tr, selector.getBookUrlSelector());
				String author = getHtml(tr, selector.getBookAuthorSelector());
				String s_status = getHtml(tr, selector.getBookStatusSelector());
				int status = Utils.getBookStatus(s_status);
				String type = getHtml(tr, selector.getBookTypeSelector());
				String newUpdateChapter = getHtml(tr, selector.getNewChapterNameSelector());
				String newUpdateChapterUrl = getHtml(tr, selector.getNewChapterUrlSelector());
				String newUpdateChapterTime = getHtml(tr, selector.getNewChapterUpdateTimeSelector());

				bookList.add(new Book(bookName, author, bookUrl, status, type, 
						newUpdateChapter, newUpdateChapterUrl, newUpdateChapterTime, new Date(), new Date()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bookList;
	}

	private String getAbsUrl(Element el, String selector) {
		if (selector != null && selector.length() > 0) {
			return el.select(selector).first().absUrl("href");
		}
		return null;
	}

	private String getHtml(Element el, String selector) {
		if (selector != null && selector.length() > 0) {
			String content = el.select(selector).first().html();
			Pattern pattern = Pattern.compile("<em>.*</em>");
			Matcher m_html = pattern.matcher(content);
			return m_html.replaceAll("");
		}
		return null;
	}

}
